import React, { useState, useEffect, useRef, useMemo, useCallback, useReducer } from 'react'
import './style/scene.scss'
import Cuboid from './cuboid'
import Moving from './moving'
// 小写字母a开头为音频
import aBirdsound from '../assets/audio/bird.wav'
import aCarStart from '../assets/audio/carStart.mp3'
import aPiano_a3 from '../assets/audio/piano_a3.mp3'
import aPiano_d3 from '../assets/audio/piano_d3.mp3'
import aError from '../assets/audio/error.mp3'

const reducer = (state, action) => {
    const obj = {}
    obj[action.type] = action.payload
    return { ...state, ...obj }
}
export default () => {
    const [isBarUp, setIsBarUp] = useState(false)
    const [isCarRun, setIsCarRun] = useState(false)
    const [sceneW, setSceneW] = useState(0)
    const [showSecondBird, setShowSecondBird] = useState(Math.random() < .33)
    const [showColorPlate, setShowColorPlate] = useState(false)

    // 修改车、杆、台
    const [{ carColor, carBrightness, carSaturate, carNum1, carNum2 }, carDispatch] = useReducer(reducer, {
        carColor: 180,
        carBrightness: .6,
        carSaturate: 3,
        carNum1: '鲁B',
        carNum2: '0R123',
    })
    const [{ barColor, barBrightness, barSaturate }, barDispatch] = useReducer(reducer, {
        barColor: 0,
        barBrightness: 1,
        barSaturate: 1
    })
    const [{ platenColor, platenBrightness, platenSaturate }, platenDispatch] = useReducer(reducer, {
        platenColor: 0,
        platenBrightness: 1,
        platenSaturate: 1
    })

    useEffect(() => {
        setSceneW(document.querySelector('.m-scene').offsetWidth)
    }, [])

    // 错误音
    const errorSound = useRef()
    const playErrorSound = () => {
        errorSound.current.play()
    }

    // 出车
    const run = () => {
        if (isCarRun) {
            playErrorSound()
            setTimeout(() => alert('已经开出去了，重来吧^_^'), 100)
            return
        }
        if (!isBarUp) {
            playErrorSound()
            setTimeout(() => alert('不抬杆就把车撞坏啦┭┮﹏┭┮'), 100)
            return
        }
        carRun()
        setTimeout(() => {
            setIsCarRun(true)
        }, 1500);
    }
    // 倒车
    const back = () => {
        if (!isCarRun) {
            playErrorSound()
            setTimeout(() => alert('开出去了才能倒车^_^'), 100)
            return
        }
        if (!isBarUp) {
            playErrorSound()
            setTimeout(() => alert('不抬杆就把车撞坏啦┭┮﹏┭┮'), 100)
            return
        }
        carRun()
        setTimeout(() => {
            setIsCarRun(false)
        }, 1500);
    }
    // 鸟叫
    const birdSound = useRef()
    const birdsong = () => {
        birdSound.current.play()
    }
    // 抬杆落杆
    const ref_aPiano_a3 = useRef()
    const setBarUp = () => {
        setIsBarUp(true)
        ref_aPiano_a3.current.play()
    }
    const ref_aPiano_d3 = useRef()
    const setBarDown = () => {
        setIsBarUp(false)
        ref_aPiano_d3.current.play()
    }

    // 车声
    const carSound = useRef()
    const carRun = () => {
        carSound.current.pause()
        carSound.current.play()
    }
    // 重来
    const reset = () => {
        setShowSecondBird(Math.random() < .33)
        // reloadScene()
        const bar = document.querySelector('.liftingLever .bar')
        const car = document.querySelector('.car')
        bar.style.transitionDuration = '0s'
        car.style.transitionDuration = '0s'
        setIsBarUp(false)
        setIsCarRun(false)
        ref_aPiano_a3.current.pause()
        ref_aPiano_d3.current.pause()
        carSound.current.pause()
        setTimeout(() => {
            bar.style.transitionDuration = '2s'
            car.style.transitionDuration = '6s'
        }, 500)
    }

    return <div className={'m-scene'}>

        {/* 白云 */}
        <div className={'clouds'}>
            <Moving v={10}><div className={'cloud'} /></Moving>
            <Moving v={50} delay={2}><div className={'cloud'} /></Moving>
        </div>

        {/* 绿树 */}
        <div className={'trees'}>
            <div className={'tree1'} />
            <div className={'tree2'} />
        </div>

        {/* 飞鸟 */}
        <div className={'birds'}>
            <Moving v={60}><div className={'flyingBird'} /></Moving>
            <audio src={aBirdsound} ref={birdSound} />
            {showSecondBird && <Moving onStart={birdsong} ><div className={'flyingBird'} style={{ filter: `hue-rotate(${Math.random() * 360}deg) brightness(${Math.random() * .8 + .7})` }} /></Moving>}
        </div>

        {/* 汽车 */}
        <div className={'car ' + (isCarRun ? 'isCarRun' : '')}>
            <div className={'carBase'} />
            <div className={'carColor '} style={{ filter: `hue-rotate(${carColor}deg) brightness(${carBrightness}) saturate(${carSaturate})` }} />
            <div className={'carNum '} >{carNum1}<span className={'dot'}>·</span>{carNum2}</div>
            <audio src={aCarStart} ref={carSound} />
        </div>

        {/* 起落杆 */}
        <div className={'liftingLever ' + (isBarUp ? 'up ' : '') + (isCarRun ? 'isCarRun' : '')}>
            {sceneW > 0 && <Cuboid
                className={'bar'}
                size={{ x: sceneW - 60, y: 10, z: 10 }}
                style={{ filter: `hue-rotate(${barColor}deg) brightness(${barBrightness}) saturate(${barSaturate})` }}
            />}
            <Cuboid
                className={'platform'}
                rotation={{ x: -15, y: -10 }}
                text={{ f: <>映源<br />科技</> }}
                size={{ x: 40, y: 100, z: 20 }}
                style={{ filter: `hue-rotate(${platenColor}deg) brightness(${platenBrightness}) saturate(${platenSaturate})` }}
            />
        </div>

        {/* 下水井盖 */}
        <div className={'wellCover'}></div>

        {/* 调色盘 */}
        {showColorPlate && <div className={'editPanel'}>
            <h4>汽车</h4>
            颜色&emsp;<input type='range' min='-180' max='180' value={carColor} onChange={e => carDispatch({ type: 'carColor', payload: e.target.value })} /><br />
            亮度&emsp;<input type='range' min='0' max='3' step='0.05' value={carBrightness} onChange={e => carDispatch({ type: 'carBrightness', payload: e.target.value })} /><br />
            饱和度<input type='range' min='0' max='5' step='0.1' value={carSaturate} onChange={e => carDispatch({ type: 'carSaturate', payload: e.target.value })} /><br />
            车牌号<span className={'carNumInput'}>
                <input maxLength='2' value={carNum1} onChange={e => carDispatch({ type: 'carNum1', payload: e.target.value })} />·
                <input maxLength='5' value={carNum2} onChange={e => carDispatch({ type: 'carNum2', payload: e.target.value.toUpperCase() })} />
            </span>
            <h4>起落杆</h4>
            颜色&emsp;<input type='range' min='-180' max='180' value={barColor} onChange={e => barDispatch({ type: 'barColor', payload: e.target.value })} /><br />
            亮度&emsp;<input type='range' min='0' max='3' step='0.05' value={barBrightness} onChange={e => barDispatch({ type: 'barBrightness', payload: e.target.value })} /><br />
            饱和度<input type='range' min='0' max='5' step='0.1' value={barSaturate} onChange={e => barDispatch({ type: 'barSaturate', payload: e.target.value })} /><br />
            <h4>控制台</h4>
            颜色&emsp;<input type='range' min='-180' max='180' value={platenColor} onChange={e => platenDispatch({ type: 'platenColor', payload: e.target.value })} /><br />
            亮度&emsp;<input type='range' min='0' max='3' step='0.05' value={platenBrightness} onChange={e => platenDispatch({ type: 'platenBrightness', payload: e.target.value })} /><br />
            饱和度<input type='range' min='0' max='5' step='0.1' value={platenSaturate} onChange={e => platenDispatch({ type: 'platenSaturate', payload: e.target.value })} /><br />
        </div>}

        {/* 调色按钮 */}
        <div className={'btnColor ' + (showColorPlate ? '' : 'rotate')} onClick={() => setShowColorPlate(!showColorPlate)}><i className={'iconfont i-color'} /></div>

        {/* 错误音 */}
        <audio src={aError} ref={errorSound} />

        {/* 底部按钮 */}
        <div className={'ctrl'}>
            <div className={'btnGroup'}>
                <button onClick={setBarUp}>抬杆</button>
                <audio src={aPiano_a3} ref={ref_aPiano_a3} />
                <button onClick={setBarDown}>落杆</button>
                <audio src={aPiano_d3} ref={ref_aPiano_d3} />
                <button onClick={run}>开出来</button>
                <button onClick={back}>倒回去</button>
                <button onClick={reset}>重来</button>
            </div>
        </div>
    </div>
}